#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings, random
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
from django.template import Context, loader
import djangoproject.settings
import _mysql as mysql
from models import *
from django import forms
import django
import djangoproject
import COOPIP_Ajax
import COOPIP_Misc
import COOPIP_Form, COOPIP_DynamicTemplate, COOPIP_Authentication, COOPIP_FormIntranet
import COOPIP_FormGeneral, COOPIP_FormCISReport
from django.db import transaction #see django bug #9964; these pages are SELECT only, so turnin over to autocommit shouldn't cause issues
import AMR, GOS, GIS, CIS


def Test(request):
    #AlarmEventNotification.objects.all().delete()
    #i = NetworkDevice.objects.filter(id=186)[0]
    #AlarmEventHistory.SendNotifications()
    #raise(Exception(str(AlarmEventHistory.objects.all().count())))
    return NetworkStatusSummary(request)


def MapViewer(request):
    OpenLayersZoom=COOPIP_Ajax.GetOpenLayersZoom(SelectionStation, SelectionSpan, 14)
    OpenLayersJavaScriptHeading=COOPIP_Ajax.GetOpenLayersJavaScriptHeading()
    OpenLayersJavaScript=COOPIP_Ajax.GetOpenLayersJavaScript(OpenLayersZoom, MapFileName, LayerName)
    t = loader.get_template('/opt/coopip/djangoproject/templates/viewer.html')
    c = Context({'OpenLayersZoom': OpenLayersZoom, 
                 'OpenLayersJavaScript': OpenLayersJavaScript,
                 'OpenLayersJavaScriptHeading': OpenLayersJavaScriptHeading})
    return HttpResponse(t.render(c))

def WriteToLog(String):
    File=open(djangoproject.settings.LogFileName, 'a')
    File.write(str(datetime.datetime.now()) + ':      ' + String + '\n')
    File.close()

def GetTagNumber(meter):
   TagNumber=meter.TagNumber
   if(TagNumber == 'None' or (not TagNumber)):
       TagNumber='Unknown' 
   return str(TagNumber)

def MeterPingDispatch(request):
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, djangoproject.settings.StatusGroups)
    if(not Permission): 
        return DefaultMainPage(LoginStatus)
    form=COOPIP_Form.LoginForm()
    Yesterday=datetime.datetime.now() - datetime.timedelta(days=1)
    OpenLayersJavaScriptHeading=COOPIP_Ajax.GetOpenLayersJavaScriptHeading()
    OpenLayersJavaScript=COOPIP_Ajax.GetOpenLayersJavaScript()
    FailedMeters=Meter.objects.filter(Symbology='failed').order_by('-LastSuccessfulPingDateTime')
    ActiveButNotAuthorizedMeters=Meter.objects.filter(Symbology='activebutnotauthorized').filter(CISIdleIndicator=True).order_by('-LastSuccessfulPingDateTime')
    NotFoundMeters=Meter.objects.filter(Symbology='activebutnotauthorized').exclude(CISIdleIndicator=True).order_by('-LastSuccessfulPingDateTime') 
    ServiceOrderMeters=Meter.objects.filter(Symbology='serviceorder').order_by('-LastSuccessfulPingDateTime')
    InvestigationMeters=Meter.objects.filter(Symbology='investigation').order_by('-InvestigationStartDateTime')
    form=COOPIP_Form.BuildAndProcessMeterForm(request,  FailedMeters, ActiveButNotAuthorizedMeters, NotFoundMeters, ServiceOrderMeters, InvestigationMeters)
    COOPIP_DynamicTemplate.UpdateDispatchMeterPingTemplate(FailedMeters, ActiveButNotAuthorizedMeters, NotFoundMeters, ServiceOrderMeters, InvestigationMeters, Username)
    form = COOPIP_Form.PopulateMeterForm(form, FailedMeters, ActiveButNotAuthorizedMeters, NotFoundMeters, ServiceOrderMeters, InvestigationMeters)

    form.setData(form.data)
    t = loader.get_template('/opt/coopip/djangoproject/templates/dynamic_dispatchmeterping' + Username + '.html')
    c = Context({'OpenLayersJavaScript': OpenLayersJavaScript,
                 'OpenLayersJavaScriptHeading': OpenLayersJavaScriptHeading,
                 'form': form})
    return HttpResponse(t.render(c))



def MeterPingReport(request):
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, djangoproject.settings.StatusGroups)

    if(not Permission): 
        return DefaultMainPage(LoginStatus)
    form=COOPIP_Form.LoginForm()
    Report='Placeholder for the meter ping report'
    form=COOPIP_Form.BuildDynamicForm(request, 'MeterPingReport')
    MeterPings=COOPIP_FormIntranet.ProcessMeterPingReportForm(form, Username, request)
    Results=[]
    try: 
        Results.append(djangoproject.models.ipbase.MeterPing.objects.all()[1].GetHeadings())
    except IOError:
        pass
    for ping in MeterPings:
        Results.append(str(ping))
    Report='\n'.join(Results)
     
    #form = COOPIP_Form.PopulateMeterPingReportForm(form)
    #raise(Exception('Here'))
    t = loader.get_template('/opt/coopip/djangoproject/templates/meterpingreport.html')
    c = Context({'form': form, 'Report': Report, 'Permission': Permission})
    return HttpResponse(t.render(c))


def DefaultMainPage(LoginStatus):
    form=COOPIP_Form.LoginForm()
    t = loader.get_template('/opt/coopip/djangoproject/templates/intranetmainpage.html')
    c = Context({'LoginStatus': LoginStatus, 'form': form})
    return HttpResponse(t.render(c))





def MeterPingDisplayTop(request):
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, djangoproject.settings.StatusGroups)
    #if(not Permission): 
    #    return DefaultMainPage(LoginStatus)
    OpenLayersJavaScriptHeading=COOPIP_Ajax.GetOpenLayersJavaScriptHeading()
    OpenLayersJavaScript=COOPIP_Ajax.GetAllMetersOpenLayersJavaScript(Top=True)
    t = loader.get_template('/opt/coopip/djangoproject/templates/meterpingdisplay.html')
    c = Context({'OpenLayersJavaScript': OpenLayersJavaScript,
                 'OpenLayersJavaScriptHeading': OpenLayersJavaScriptHeading})
    return HttpResponse(t.render(c))







def BlinkCountReport(request):
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, ['COOPIP_Editor_Technology', 'COOPIP_Editor_Operations'])
    if(not Permission): 
        return DefaultMainPage(LoginStatus)
    #When using authentication, check for application permission here.
    import datetime
    #Meter Blink Tasks needed
    #Run MeterBlinkCounts only on new dates (Change************, select the last one with a count to be the starting point)
    #Review Flag Meter Blinks code Before running it, should be ok
    #Create a MeterBlinkReport View
    #Headings:
    #MeterNumber        MeterBlink30        MeterBlink60         MeterBlink90   MeterBlink180      MeterBlink360
    #Add these as database fields to the SerialNumber table, so that they can be precalculated, plus add a MeterBlinkFlagLastCalculateDate????
    #Create a Detail View
    #Meter Number, Total Blinks, Calculated Blinks, Date, Flag Indicator [Show all blinks for the meter, in reverse date order]
    Report=[]
    Report.append('Meter'.ljust(20) + '30 Days'.ljust(10) + '60 Days'.ljust(10) + '90 Days'.ljust(10) + '180 Days'.ljust(10) + '360 Days'.ljust(10))
    Meters=Meter.objects.all().order_by('SerialNumber')
    for meter in Meters:
        Report.append(str(meter.SerialNumber).ljust(20) + str(meter.MeterBlink30).ljust(10) + str(meter.MeterBlink60).ljust(10) +\
                      str(meter.MeterBlink90).ljust(10) + str(meter.MeterBlink180).ljust(10) + \
                      str(meter.MeterBlink360).ljust(10))  
    Report='\n'.join(Report)      
    t = loader.get_template('/opt/coopip/djangoproject/templates/generic.html')
    c = Context({'Report': Report})
    return HttpResponse(t.render(c))


def BlinkCountReportDetail(request, MeterNumber):
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, djangoproject.settings.StatusGroups)
    if(not Permission): 
        return DefaultMainPage(LoginStatus)
    #When using authentication, check for application permission here.
    import datetime
    #Meter Blink Tasks needed
    #Run MeterBlinkCounts only on new dates (Change************, select the last one with a count to be the starting point)
    #Review Flag Meter Blinks code Before running it, should be ok
    #Create a MeterBlinkReport View
    #Headings:
    #MeterNumber        MeterBlink30        MeterBlink60         MeterBlink90   MeterBlink180      MeterBlink360
    #Add these as database fields to the SerialNumber table, so that they can be precalculated, plus add a MeterBlinkFlagLastCalculateDate????
    #Create a Detail View
    #Meter Number, Total Blinks, Calculated Blinks, Date, Flag Indicator [Show all blinks for the meter, in reverse date order]
    Report=[]
    Report.append('Meter'.ljust(20) + 'Total Blinks'.ljust(10) + 'Calculated Blinks'.ljust(10) + 'Flag'.ljust(10))
    MeterBlinks=MeterBlink.objects.filter(SerialNumber=MeterNumber)
    for meterBlink in MeterBlinks:
        Report.append(str(MeterNumber).ljust(20) + str(meterBlink.Count).ljust(10) + str(CalculatedBlinks).ljust(10) + str(meter.FlagIndicator).ljust(10))                  
    t = loader.get_template('/opt/coopip/djangoproject/templates/generic.html')
    c = Context({'form': form, 'Report': Report})
    return HttpResponse(t.render(c))

def ReverseRotationReport(request):
    LoginStatus='No Logins Implemented for COOPIP'
    Meters=Meter.objects.all()
    t = locader.get_template('/opt/coopip/djangoproject/templates/reverserotation.html')
    c = Contect({'LoginStatus':LoginStatus})
    return HttpResponse(t.render(c))




def ImportData(request):
    LoginStatus='No Logins Implemented for COOPIP, ImportData'
    a = LocationMeter()
    a.GetLocationMeterFromCIS()
    t = loader.get_template('/opt/coopip/djangoproject/templates/mainmenu.html')
    c = Context({'LoginStatus': LoginStatus})
    return HttpResponse(t.render(c))
    pass




def NetworkStatusDetail(request):
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, djangoproject.settings.StatusGroups)
    if(not Permission): 
        return DefaultMainPage(LoginStatus)
    #When using authentication, check for application permission here.
    import datetime
    StartDate=datetime.datetime.now() - datetime.timedelta(days=2)
    SummaryReport=[]
    SummaryReport.append('Network Status Summary Report\n\n')

    #ProST Radio Summary Section *********************************************
    FirstRadioFailedIndicator=True
    ProSTRadios=NetworkDevice.objects.filter(NetworkDeviceModel__Name='ProST Radio')
    for radio in ProSTRadios:
        FailedTests=NetworkDeviceTest.objects.filter(NetworkDevice=radio).filter(DateTime__gte=StartDate).filter(EffectiveSignalToNoiseRatio=None).count()
        if(FailedTests):
            if(FirstRadioFailedIndicator):
                SummaryReport.append('Recent ProST Radio Lost Contact'.ljust(33) + 'No Response'.ljust(12) + ''.ljust(5) + 'Total Attempts'.ljust(14))
                FirstRadioFailedIndicator=False
            TotalTests=NetworkDeviceTest.objects.filter(NetworkDevice=radio).filter(DateTime__gte=StartDate).count()
            LatestAttempt=NetworkDeviceTest.objects.filter(NetworkDevice=radio).filter(DateTime__gte=StartDate).order_by('-DateTime')[0]
            if(LatestAttempt.EffectiveSignalToNoiseRatio):
                LatestAttemptMessage = 'Last Attempt Succeeded:  ' + str(LatestAttempt.DateTime)
            else:
                LatestAttemptMessage = 'Last Attempt Failed:  ' + str(LatestAttempt.DateTime)
            SummaryReport.append(str(radio).ljust(33) + str(FailedTests).ljust(12) + ' /'.ljust(5) + str(TotalTests).ljust(14))
    #End ProST Radio Summary Section *********************************************

    #Moxa Summary Section***********************************************
    Moxae=NetworkDevice.objects.filter(NetworkDeviceModel__Name='Moxa')
    for moxa in Moxae:
        FailedTests=NetworkDeviceTest.objects.filter(NetworkDevice=moxa).filter(DateTime__gte=StartDate).exclude(ResponseIndicator=True).count()
        if not FailedTests:
            continue
        TotalTests=NetworkDeviceTest.objects.filter(NetworkDevice=moxa).filter(DateTime__gte=StartDate).count()
        SummaryReport.append(str(moxa).ljust(33) + str(FailedTests).ljust(12) + ' /'.ljust(5) + str(TotalTests).ljust(14))     
    SummaryReport='\n'.join(SummaryReport)   
    #End Moxa Summary Section*******************************************
    Report=[]
    NetworkDevices=NetworkDevice.objects.all().order_by('id')
    for device in NetworkDevices:
        Tests=NetworkDeviceTest.objects.filter(NetworkDevice=device).order_by('-DateTime')
        MaxResults=1000
        CurrentResults=0
        Report.append(str(device.Name).ljust(22) + str(device.IPAddress).ljust(25))
        Report.append('     ' + 'Response'.ljust(10) + 'SNR'.ljust(10) + 'Received Signal Strength'.ljust(25) + 'Transmit Power'.ljust(20) + 'Date/Time'.ljust(19))
        for test in Tests:
            CurrentResults = CurrentResults + 1
            if(CurrentResults == 1000):
                break
            Report.append('     ' + str(test.ResponseIndicator).ljust(10) + str(test.SignalToNoiseRatio).ljust(10) + str(test.ReceivedSignalStrength).ljust(25) +\
                          str(test.TransmitPower).ljust(20) + str(test.DateTime)[:16].ljust(19))
        Report.append('')
        Report.append('')
    ReportName='Network Status Report'
    Report = '\n'.join(Report)
    t = loader.get_template('/opt/coopip/djangoproject/templates/networkstatusdetail.html')
    c = Context({'Report': Report, 'ReportName': ReportName, 'SummaryReport':SummaryReport})
    return HttpResponse(t.render(c))







def GetGISOutdoorlightingRateString(i): #i is outdoorlightrate object from GIS
    if(i):
        return str(i.unitname) + '  Type:  ' + str(i.type) + ' Wattage:  ' + str(i.wattage) + ' KWH:  ' + str(i.kwh) + ' Desc:  ' + str(i.description)
    else:
        return "Unknown Rate"







def ImportOutdoorLightingConditionsFromGIS(Reimport=False):
    if(Reimport == False):
        Conditions=GIS.Coopgiscondition.objects.filter(priorityoutdoorlightingconversionindicator=True).exclude(
                       outdoorlightbillingworkstartedindicator=True).exclude(
                       archivedindicator=True).exclude(
                       deletedindicator=True).order_by('id')
    else:
        Conditions=GIS.Coopgiscondition.objects.filter(priorityoutdoorlightingconversionindicator=True).filter(
                       outdoorlightbillingworkstartedindicator=True).filter(
                       outdoorlightsendbacktobillingphaseindicator=True).exclude(
                       archivedindicator=True).exclude(
                       deletedindicator=True).order_by('id')

    for i in Conditions:
        if(Reimport == False):
            New=djangoproject.models.ipbase.OutdoorLightingConversion()
        else:
            TempDebug = i.id
            try:
                New=djangoproject.models.ipbase.OutdoorLightingConversion.objects.filter(gisid=i.id)[0]
            except IndexError:
                continue  #FIXME Need to log this somewhere
            New.OutdoorLightBillingPhaseIndicator=True
            New.OutdoorLightGISPhaseIndicator=False
        New.gisid = i.id
        New.gispoint = i.point
        New.gisstationidentifier = i.stationidentifier
        New.gistagnumber = i.tagnumber
        try:
            gislights = GIS.Coopgisassembly.objects.filter(station__id=i.stationidentifier).filter(compatibleunit__lightindicator=True)
        except:
            gislights = None
        if(gislights and len(gislights) == 1):
            if(not i.outdoorlightmapnumber):
                i.outdoorlightmapnumber = gislights[0].mapnumber
                i.save()

        New.gisoutdoorlightmapnumber = i.outdoorlightmapnumber
        New.gisoutdoorlightmeternumber = str(i.outdoorlightmeternumber).strip()
        New.gisoutdoorlightmetermapnumber = i.outdoorlightmetermapnumber
        New.gisoutdoorlightidleindicator = i.outdoorlightidleindicator
        New.gisneedsretirementindicator = i.needsretirementindicator
        New.gisoutdoorlightadditionalbillingpolecount = i.outdoorlightadditionalbillingpolecount
        try:
            New.gisoutdoorlightratename = GetGISOutdoorlightingRateString(GIS.Coopgisoutdoorlightrate.objects.filter(id=i.outdoorlightrate)[0])
        except IndexError:
            New.gisoutdoorlightratename = 'UNKNOWN'


        New.gisoutdoorlightcustomerownspoleindicator = i.outdoorlightcustomerownspoleindicator
        New.gisoutdoorlightcustomerownslightindicator = i.outdoorlightcustomerownslightindicator
        New.giscreatedatetime = i.createdatetime
        New.giscreateusername = i.createusername
        New.giscircuitnumbers = i.circuitnumbers
        if(GIS.Coopgisoutdoorlightconsumerownedlightcount.objects.filter(metermapnumber=i.outdoorlightmetermapnumber)):
            MemberOwnedLightCount = GIS.Coopgisoutdoorlightconsumerownedlightcount.objects.filter(metermapnumber=i.outdoorlightmetermapnumber)[0].lightcount
        else:
            MemberOwnedLightCount = 0
        New.gisoutdoorlightconsumerownedlightcount=MemberOwnedLightCount
        New.CreateDateTime=datetime.datetime.now()
        try:
            gispoles = GIS.Coopgisassembly.objects.filter(station__id=i.stationidentifier).filter(compatibleunit__poleindicator=True)
        except:
            gispoles = None
        if(gispoles):
            New.gispolecompatibleunitname = gispoles[0].compatibleunit.name
        else:
            New.gispolecompatibleunitname=''
        
        try:
            Coopgissubstationid = str(GIS.Substationcircuit.objects.filter(circuitnumber=New.giscircuitnumbers.split(',')[0])[0].substation.id)
            New.gissubstation = str(GIS.Coopgissubstation.objects.filter(id=int(Coopgissubstationid))[0].name)
        except:
            pass

        if(gispoles and not New.gistagnumber):
            New.gistagnumber = gispoles[0].tagnumber
        New.save()
        New.cismemberseperator = ''
        New.UpdateFieldsFromCIS()
        i.outdoorlightbillingworkstartedindicator = True
        i.outdoorlightsendbacktobillingphaseindicator = False
        i.outdoorlightgisphaseindicator = False
        i.save()



class blank():
    pass

def OutdoorLightingBillingPhaseTable(request):
    """View that guides users along configuring Outdoor Lighting in the CIS after data collection has been completed in the GIS"""
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, ['COOPIP_CISUser', 'COOPIP_RevenueProtectionAdmin'])
    if(not Permission):  
        return DefaultMainPage(LoginStatus)
    ImportOutdoorLightingConditionsFromGIS()
    ImportOutdoorLightingConditionsFromGIS(Reimport=True)

    #List all Conditions that need to be worked on the form
    #Also list the last 50 conditions that have been worked at the bottom of the form so they can be reviewed/modified if needed.
    Conditions1 = djangoproject.models.ipbase.OutdoorLightingConversion.objects.all().exclude(BillingSetupCompleteIndicator = True).exclude(OutdoorLightGISPhaseIndicator=True).exclude(DeleteIndicator=True).order_by('gisid')
    Conditions2 = djangoproject.models.ipbase.OutdoorLightingConversion.objects.all().filter(BillingSetupCompleteIndicator=True).exclude(DeleteIndicator=True).order_by('-BillingSetupCompleteDateTime')
    Conditions=[]
    for i in Conditions1:
        Conditions.append(i)
    Count = 0
    for i in Conditions2:
        Conditions.append(i)
        Count = Count + 1
        if(Count > 50):
            break
    Coordinates=blank()
    i = 0
    while(i < len(Conditions)):
        exec "Coordinates.Longitude" + str(i) + ", Coordinates.Latitude" + str(i) + "=COOPIP_Ajax.GetLatitudeLongitude(point=Conditions[" + str(i) + "].gispoint, SRID=djangoproject.settings.COOPIPGPSSRID)"
        exec "Coordinates.Longitude" + str(i) + "= abs(Coordinates.Longitude" + str(i) + ")"
        exec "Coordinates.Latitude" + str(i) + "= abs(Coordinates.Latitude" + str(i) + ")"
        exec "Coordinates.Station" + str(i) + "= Conditions[" + str(i) + "].gisstationidentifier"
        i = i + 1
    
    SpecialBuildFormDataDict={}
    SpecialBuildFormDataDict['Conditions'] = Conditions
    SpecialBuildFormDataDict['request'] = request
    form = COOPIP_Form.BuildDynamicForm(request, 'OutdoorLightingBillingPhaseTable', SpecialBuildFormDataDict)
    COOPIP_FormCISReport.ProcessOutdoorLightingBillingPhaseTableForm(form, Username)
    #Rebuild The Form to account for any changes that were made processing the form
    Conditions1 = djangoproject.models.ipbase.OutdoorLightingConversion.objects.all().exclude(BillingSetupCompleteIndicator = True).exclude(OutdoorLightGISPhaseIndicator=True).exclude(DeleteIndicator=True).order_by('gisid')
    Conditions2 = djangoproject.models.ipbase.OutdoorLightingConversion.objects.all().filter(BillingSetupCompleteIndicator=True).exclude(DeleteIndicator=True).order_by('-BillingSetupCompleteDateTime')
    Conditions=[]
    for i in Conditions1:
        Conditions.append(i)
    Count = 0
    for i in Conditions2:
        Conditions.append(i)
        Count = Count + 1
        if(Count > 50):
            break
    SpecialBuildFormDataDict['Conditions'] = Conditions
    form = COOPIP_Form.BuildDynamicForm(request, 'OutdoorLightingBillingPhaseTable', SpecialBuildFormDataDict)
    form=COOPIP_FormCISReport.PopulateOutdoorLightingBillingPhaseTableForm(form, Conditions, Username)
    #End Form Rebuild Section
    COOPIP_DynamicTemplate.UpdateOutdoorLightingBillingPhaseTableTemplate(Username, Conditions)
    t = loader.get_template('/opt/coopip/djangoproject/templates/dynamic_outdoorlightingbillingphasetable_' + Username + '.html')
    c = Context({'LoginStatus': LoginStatus, 'form': form, 'Permission': Permission, 'Coordinates': Coordinates})
    return HttpResponse(t.render(c))

    EditorGroups=djangoproject.settings.DispatchEditorGroups
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, EditorGroups)
    #When using authentication, check for application permission here.



def Logout(request):
    django.contrib.auth.logout(request) 
    t=loader.get_template('/opt/coopip/djangoproject/templates/logout.html')
    c=Context({})
    return HttpResponse(t.render(c))

def GetSizeAndLargestUnit(Input):
    Bytes=float(Input)
    DivisionCount=0
    CountDict={0:'B', 1:'KB', 2:'MB', 3:'GB', 4:'TB'}
    while Bytes >= 1024:
        Bytes=Bytes/1024.0
        DivisionCount+=1
    return str(int(Bytes)) + ' ' + CountDict[DivisionCount]



def ServerStatus(request):
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, djangoproject.settings.StatusGroups)
    if(not Permission): 
        return DefaultMainPage(LoginStatus)
    Temp=[]
    for server in Server.objects.all().order_by('Name'):
        ServerStatusLogs=ServerStatusLog.objects.filter(Server=server).order_by('-CreateDateTime')
        if not ServerStatusLogs.count():
            Temp.append('ERROR: No status logs found for ' + server.Name)
            continue
        LatestLog=ServerStatusLogs[0]
        try:
            MemoryInUse=str(round(LatestLog.TotalMemory-LatestLog.FreeMemory,2)) + '/' + str(LatestLog.TotalMemory)
            SwapInUse=str(round(LatestLog.TotalSwap-LatestLog.FreeSwap, 2)) + '/' + str(LatestLog.TotalSwap)
        except TypeError:
            MemoryInUse='N/A'
            SwapInUse='N/A'
        Temp.append('\n\nServer: ' + server.Name)
        Temp.append('Memory In Use: ' + MemoryInUse)
        Temp.append('Swap In Use: ' + SwapInUse)
        Drives=Drive.objects.filter(Server=server)
        Temp.append('\nDrive'.ljust(15) + 'Free Space'.ljust(30) + 'Total Size'.ljust(30) + 'Utilization'.ljust(30))
        for drive in Drives:
            LatestDriveLog=DriveLog.objects.filter(Drive=drive).filter(ServerStatusLog=LatestLog)[0]
            PercentInUse=round((LatestDriveLog.TotalSpace - LatestDriveLog.FreeSpace) / LatestDriveLog.TotalSpace,2)
            Temp.append(drive.Name.ljust(15) 
                      + GetSizeAndLargestUnit(LatestDriveLog.FreeSpace).ljust(30) 
                      + GetSizeAndLargestUnit(LatestDriveLog.TotalSpace).ljust(30) 
                      + (str(PercentInUse*100.0) + '%').ljust(30))
        if not LatestLog.BackupRemoteDateTime:
            Temp.append(LatestLog.CreateDateTime.strftime('%m/%d/%Y %H:%M') + ' status lacks backup information')
            continue
        Temp.append('\nLog Created'.ljust(20) + 'Domain Backup'.ljust(15) + 'Size (Bytes)'.ljust(20) + 'Local Backup'.ljust(15) + 'Size'.ljust(20))
        for log in ServerStatusLogs[:3]:
            Temp.append(log.CreateDateTime.strftime('%m/%d/%Y %H:%M').ljust(20)  
                      + log.BackupRemoteDateTime.strftime('%m/%d/%Y').ljust(15) 
                      + str(int(log.BackupRemoteSize)).ljust(20)
                      + log.BackupLocalDateTime.strftime('%m/%d/%Y').ljust(15) 
                      + str(int(log.BackupLocalSize)).ljust(20))

            
    ReportName='Server Status Report'    
    Report ='\n'.join(Temp)
    t = loader.get_template('/opt/coopip/djangoproject/templates/serverstatus.html')
    c = Context({'Report': Report, 'ReportName': ReportName})
    return HttpResponse(t.render(c))

def GetDirectionFromBearing(Bearing):
    if Bearing == 0:
        return 'N'
    elif Bearing < 90:
        return 'NE'
    elif Bearing == 90:
        return 'E'
    elif Bearing < 180:
        return 'SE'
    elif Bearing == 180:
        return 'S'
    elif Bearing < 270:
        return 'SW'
    elif Bearing == 270:
        return 'W'
    else:
        return 'NW'



